package com.zhishu.system.interceptor;

import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler;

import com.zhishu.system.util.Const;


/**
 * 
 * 类名称：LoginHandlerInterceptor.java 类描述：
 * 
 * @author FH 作者单位： 联系方式： 创建时间：2015年1月1日
 * @version 1.6
 */
public class SessionInterceptor extends HandlerInterceptorAdapter {
	private Set<String> writeUrls;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		if (handler instanceof DefaultServletHttpRequestHandler) {
			return super.preHandle(request, response, handler);
		}

		boolean pass = false;

		String path = request.getServletPath();
		HttpSession session = request.getSession();
		Object user = (Object) session.getAttribute(Const.SESSION_USER);

		if (user != null) {
			path = path.substring(1, path.length());
			return true;
		} else {

			// 不需要登录验证
			for (String url : writeUrls) {
				if (path.matches(url)) {
					pass = true;
				}
			}

			if (pass) {
				return true;
			}

			if (!pass) {
				String context = request.getContextPath();
				response.sendRedirect(context + "/" );
			}

			return pass;

		}

	}

	public Set<String> getWriteUrls() {
		return writeUrls;
	}

	public void setWriteUrls(Set<String> writeUrls) {
		this.writeUrls = writeUrls;
	}

}
